package com.wutongyu.mannyburger;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.chip.Chip;
import com.google.android.material.chip.ChipGroup;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.wutongyu.mannyburger.AllOrderActivity;

import java.util.ArrayList;
import java.util.List;

public class OrderFragment extends Fragment implements CartManager.CartChangeListener, CartManager.CartClearListener {

    private static final String TAG = "OrderFragment";
    private RecyclerView recyclerViewProducts;
    private Button allOrderButton;
    private Button submitOrderButton;
    private FloatingActionButton toggleMusicButton;
    private TextView bottomCartTextView;
    private TextView emptyProductsView;
    private TextView cartBadge;
    private ImageView cartIcon; // 添加购物车图标引用
    private EditText searchEditText;
    private ChipGroup categoryChipGroup;
    
    private ProductRecyclerAdapter productAdapter;
    private ProductDatabaseHelper dbHelper;
    private List<Product> allProducts; // 所有商品
    private List<Product> displayedProducts; // 当前显示的商品
    private CartManager cartManager; // 购物车管理器
    
    private String currentCategory = "全部"; // 当前选中分类
    private String searchQuery = ""; // 当前搜索关键词
    private AlertDialog cartDialog; // 购物车对话框

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_order, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Log.d(TAG, "onViewCreated: 开始初始化视图");

        // 绑定控件
        recyclerViewProducts = view.findViewById(R.id.recyclerViewProducts);
        allOrderButton = view.findViewById(R.id.all_order_button);
        submitOrderButton = view.findViewById(R.id.submit_order_button);
        bottomCartTextView = view.findViewById(R.id.bottomCartTextView);
        toggleMusicButton = view.findViewById(R.id.toggle_music_button);
        searchEditText = view.findViewById(R.id.search_edit_text);
        categoryChipGroup = view.findViewById(R.id.category_chip_group);
        emptyProductsView = view.findViewById(R.id.emptyProductsView);
        cartBadge = view.findViewById(R.id.cartBadge);
        cartIcon = view.findViewById(R.id.cartIcon); // 获取购物车图标引用

        Log.d(TAG, "onViewCreated: 控件绑定完成");

        // 初始化购物车管理器
        cartManager = CartManager.getInstance();
        cartManager.addCartChangeListener(this);
        cartManager.addCartClearListener(this);
        
        // 加载购物车数据
        cartManager.loadCart(requireContext());
        Log.d(TAG, "onViewCreated: 购物车加载完成");

        // 初始化数据库帮助类
        dbHelper = new ProductDatabaseHelper(requireContext());
        Log.d(TAG, "onViewCreated: 数据库帮助类初始化完成");

        // 加载商品数据
        loadProducts();
        Log.d(TAG, "onViewCreated: 商品数据加载完成");

        // 设置RecyclerView
        setupRecyclerView();
        Log.d(TAG, "onViewCreated: RecyclerView设置完成");

        // 初始化购物车UI
        updateCartUI();
        Log.d(TAG, "onViewCreated: 购物车UI更新完成");

        // 设置按钮监听器
        setupButtonClickListeners();
        Log.d(TAG, "onViewCreated: 按钮监听器设置完成");
        
        // 设置分类标签监听器
        setupCategoryChips();
        Log.d(TAG, "onViewCreated: 分类标签监听器设置完成");
        
        // 设置搜索功能
        setupSearch();
        Log.d(TAG, "onViewCreated: 搜索功能设置完成");
        
        // 设置滑动删除功能
        setupItemTouchHelper();
        Log.d(TAG, "onViewCreated: 滑动删除功能设置完成");
        
        // 设置购物车相关区域的点击事件
        setupCartClickListeners();
        Log.d(TAG, "onViewCreated: 购物车点击事件设置完成");
        
        // 确保初始过滤
        filterProducts();
        Log.d(TAG, "onViewCreated: 初始过滤完成");
    }

    // 设置购物车相关区域的点击事件
    private void setupCartClickListeners() {
        // 购物车图标点击事件
        if (cartIcon != null) {
            cartIcon.setOnClickListener(v -> {
                showCartDialog();
            });
        }
        
        // 购物车文本区域点击事件
        if (bottomCartTextView != null) {
            bottomCartTextView.setOnClickListener(v -> {
                showCartDialog();
            });
        }
        
        // 获取底部布局容器
        View bottomCartLayout = getView().findViewById(R.id.bottomCartLayout);
        if (bottomCartLayout != null) {
            // 为底部布局容器添加点击事件，但我们不会在这里设置，
            // 因为这会导致点击事件与结算按钮冲突
            // 我们可以利用CardView（底部购物车容器）的点击事件
        }
        
        // 获取整个购物车栏的父容器CardView
        View bottomCartContainer = getView().findViewById(R.id.bottomCart);
        if (bottomCartContainer != null) {
            // 为CardView添加点击事件
            bottomCartContainer.setOnClickListener(v -> {
                // 如果点击发生在结算按钮上，我们不应该显示购物车对话框
                // 这个点击事件会被结算按钮自己的点击事件覆盖，因为结算按钮是CardView的子视图
                showCartDialog();
            });
        }
    }
    
    // 显示购物车对话框
    private void showCartDialog() {
        // 获取当前购物车商品
        List<CartItem> cartItems = cartManager.getCartItems();
        
        // 如果购物车为空，显示提示
        if (cartItems.isEmpty()) {
            Toast.makeText(requireContext(), "购物车是空的", Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        View dialogView = getLayoutInflater().inflate(R.layout.dialog_cart, null);
        builder.setView(dialogView);
        
        // 初始化对话框控件
        RecyclerView cartRecyclerView = dialogView.findViewById(R.id.cart_items_recyclerview);
        TextView emptyCartView = dialogView.findViewById(R.id.empty_cart_view);
        TextView totalPriceTextView = dialogView.findViewById(R.id.dialog_cart_total_price);
        Button btnClear = dialogView.findViewById(R.id.dialog_btn_clear);
        Button btnContinue = dialogView.findViewById(R.id.dialog_btn_continue);
        Button btnCheckout = dialogView.findViewById(R.id.dialog_btn_checkout);
        
        // 设置购物车商品列表
        cartRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
        
        // 创建适配器
        CartDialogAdapter adapter = new CartDialogAdapter(
                requireContext(), 
                new ArrayList<>(cartItems), 
                new CartDialogAdapter.CartDialogListener() {
                    @Override
                    public void onCartUpdated(List<CartItem> updatedCartItems, double totalPrice) {
                        // 更新总价显示
                        totalPriceTextView.setText("总计: ¥" + String.format("%.2f", totalPrice));
                        
                        // 检查是否为空
                        if (updatedCartItems.isEmpty()) {
                            cartRecyclerView.setVisibility(View.GONE);
                            emptyCartView.setVisibility(View.VISIBLE);
                            btnCheckout.setEnabled(false);
                            btnClear.setEnabled(false);
                        } else {
                            cartRecyclerView.setVisibility(View.VISIBLE);
                            emptyCartView.setVisibility(View.GONE);
                            btnCheckout.setEnabled(true);
                            btnClear.setEnabled(true);
                        }
                    }
                });
        
        cartRecyclerView.setAdapter(adapter);
        
        // 设置总价显示
        totalPriceTextView.setText("总计: ¥" + String.format("%.2f", cartManager.getTotalPrice()));
        
        // 设置按钮点击事件
        btnClear.setOnClickListener(v -> {
            // 显示确认对话框
            new AlertDialog.Builder(requireContext())
                    .setTitle("清空购物车")
                    .setMessage("确定要清空购物车吗？")
                    .setPositiveButton("确定", (dialog, which) -> {
                        cartManager.clearCart();
                        adapter.updateCartItems(cartManager.getCartItems());
                        totalPriceTextView.setText("总计: ¥0.00");
                        cartRecyclerView.setVisibility(View.GONE);
                        emptyCartView.setVisibility(View.VISIBLE);
                        btnCheckout.setEnabled(false);
                        btnClear.setEnabled(false);
                        
                        // 强制更新商品列表适配器，确保所有商品的数量显示为0
                        if (productAdapter != null) {
                            productAdapter.notifyDataSetChanged();
                            
                            // 遍历所有显示中的商品，强制更新数量显示
                            for (int i = 0; i < recyclerViewProducts.getChildCount(); i++) {
                                View itemView = recyclerViewProducts.getChildAt(i);
                                if (itemView != null) {
                                    TextView quantityView = itemView.findViewById(R.id.product_quantity);
                                    if (quantityView != null) {
                                        quantityView.setText("0");
                                    }
                                    
                                    ImageButton btnDecrease = itemView.findViewById(R.id.btn_decrease);
                                    if (btnDecrease != null) {
                                        btnDecrease.setVisibility(View.GONE);
                                    }
                                }
                            }
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show();
        });
        
        btnContinue.setOnClickListener(v -> {
            if (cartDialog != null) {
                cartDialog.dismiss();
            }
        });
        
        btnCheckout.setOnClickListener(v -> {
            if (cartDialog != null) {
                cartDialog.dismiss();
            }
            
            // 跳转到结算页面，复用原有逻辑
            Intent intent = new Intent(getActivity(), OrderActivity.class);
            
            // 将选中商品信息格式化后传递
            StringBuilder orderDetails = new StringBuilder();
            for (CartItem cartItem : cartItems) {
                Product product = cartItem.getProduct();
                int quantity = cartItem.getQuantity();
                if (quantity > 0) {
                    orderDetails.append(product.getName())
                            .append(" x").append(quantity)
                            .append(" - ¥").append(String.format("%.2f", product.getPrice() * quantity))
                            .append("\n");
                }
            }
            
            intent.putExtra("order_details", orderDetails.toString());
            intent.putExtra("total_price", cartManager.getTotalPrice());
            startActivity(intent);
        });
        
        // 创建并显示对话框
        cartDialog = builder.create();
        cartDialog.show();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 重新加载购物车数据，用于处理从OrderActivity返回的情况
        cartManager.loadCart(requireContext());
        updateCartUI();
    }
    
    @Override
    public void onPause() {
        super.onPause();
        // 保存购物车数据
        cartManager.saveCart(requireContext());
    }

    // 加载所有商品数据
    private void loadProducts() {
        Log.d(TAG, "loadProducts: 开始加载商品数据");
        
        // 从数据库加载所有商品
        allProducts = dbHelper.getAllProducts();
        
        if (allProducts == null || allProducts.isEmpty()) {
            Log.d(TAG, "loadProducts: 数据库中没有商品数据");
            allProducts = new ArrayList<>();
        }
        
        // 初始化显示列表，包含所有商品
        displayedProducts = new ArrayList<>(allProducts);
        
        Log.d(TAG, "loadProducts: 已加载商品数量 = " + allProducts.size() + ", displayedProducts初始化大小 = " + displayedProducts.size());
        
        // 添加详细日志，记录所有加载的商品及其分类信息
        Log.d(TAG, "=== 已加载的商品分类信息 ===");
        for (Product product : allProducts) {
            Log.d(TAG, "商品ID: " + product.getId() + 
                  ", 名称: '" + product.getName() + 
                  "', 分类: '" + product.getCategory() + "'");
        }
        Log.d(TAG, "总共加载了 " + allProducts.size() + " 个商品");
    }
    
    // 设置RecyclerView
    private void setupRecyclerView() {
        Log.d(TAG, "setupRecyclerView: 开始设置RecyclerView");
        
        // 确保显示产品列表不为空
        if (displayedProducts == null) {
            Log.d(TAG, "setupRecyclerView: displayedProducts为null，初始化新列表");
            displayedProducts = new ArrayList<>(allProducts);
        }
        
        recyclerViewProducts.setLayoutManager(new LinearLayoutManager(requireContext()));
        recyclerViewProducts.setItemAnimator(new DefaultItemAnimator());
        
        Log.d(TAG, "setupRecyclerView: 初始化适配器，商品数量: " + displayedProducts.size());
        productAdapter = new ProductRecyclerAdapter(requireContext(), displayedProducts);
        recyclerViewProducts.setAdapter(productAdapter);
        
        // 确保适配器知道数据变化
        productAdapter.notifyDataSetChanged();
        
        // 添加RecyclerView监听装饰器，帮助诊断问题
        recyclerViewProducts.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NonNull android.graphics.Canvas c, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
                if (parent.getChildCount() == 0 && !displayedProducts.isEmpty()) {
                    Log.d(TAG, "RecyclerView绘制：没有可见子项但displayedProducts不为空，数量: " + displayedProducts.size());
                } else {
                    Log.d(TAG, "RecyclerView绘制：可见子项数量: " + parent.getChildCount() + 
                           ", 适配器项目数量: " + parent.getAdapter().getItemCount());
                }
            }
        });
        
        // 添加数据观察者，监控适配器数据变化
        productAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                Log.d(TAG, "适配器数据变化事件：onChanged()，当前项目数: " + productAdapter.getItemCount());
                checkIfEmpty();
            }
            
            @Override
            public void onItemRangeChanged(int positionStart, int itemCount) {
                Log.d(TAG, "适配器数据变化事件：onItemRangeChanged(), 范围: " + positionStart + " - " + (positionStart + itemCount - 1));
            }
            
            @Override
            public void onItemRangeInserted(int positionStart, int itemCount) {
                Log.d(TAG, "适配器数据变化事件：onItemRangeInserted(), 范围: " + positionStart + " - " + (positionStart + itemCount - 1));
            }
            
            @Override
            public void onItemRangeRemoved(int positionStart, int itemCount) {
                Log.d(TAG, "适配器数据变化事件：onItemRangeRemoved(), 范围: " + positionStart + " - " + (positionStart + itemCount - 1));
            }
        });
        
        // 检查列表是否为空并显示相应UI
        checkIfEmpty();
        Log.d(TAG, "setupRecyclerView: RecyclerView设置完成");
    }
    
    // 检查列表是否为空
    private void checkIfEmpty() {
        Log.d(TAG, "checkIfEmpty: displayedProducts.size() = " + displayedProducts.size() + ", recyclerView可见性: " + 
            (recyclerViewProducts.getVisibility() == View.VISIBLE ? "可见" : "不可见") + 
            ", emptyView可见性: " + (emptyProductsView.getVisibility() == View.VISIBLE ? "可见" : "不可见"));
            
        if (displayedProducts == null || displayedProducts.isEmpty()) {
            Log.d(TAG, "显示列表为空，设置emptyView为可见");
            recyclerViewProducts.setVisibility(View.GONE);
            emptyProductsView.setVisibility(View.VISIBLE);
        } else {
            Log.d(TAG, "显示列表有" + displayedProducts.size() + "个商品，设置recyclerView为可见");
            recyclerViewProducts.setVisibility(View.VISIBLE);
            emptyProductsView.setVisibility(View.GONE);
            
            // 确保RecyclerView有一个有效的布局管理器
            if (recyclerViewProducts.getLayoutManager() == null) {
                recyclerViewProducts.setLayoutManager(new LinearLayoutManager(requireContext()));
                Log.d(TAG, "为RecyclerView设置了新的LayoutManager");
            }
            
            // 确保RecyclerView有适配器
            if (recyclerViewProducts.getAdapter() == null && productAdapter != null) {
                recyclerViewProducts.setAdapter(productAdapter);
                Log.d(TAG, "为RecyclerView设置了适配器");
            }
            
            // 如果适配器存在，检查其项目计数
            if (productAdapter != null) {
                Log.d(TAG, "适配器项目计数: " + productAdapter.getItemCount());
                if (productAdapter.getItemCount() == 0) {
                    // 适配器项目为0，但displayedProducts有内容，强制更新适配器
                    productAdapter.updateProductList(new ArrayList<>(displayedProducts));
                    productAdapter.notifyDataSetChanged();
                    Log.d(TAG, "强制更新适配器，新计数: " + productAdapter.getItemCount());
                }
            }
        }
    }
    
    // 设置商品滑动删除功能
    private void setupItemTouchHelper() {
        ItemTouchHelper.SimpleCallback simpleCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false; // 不支持拖动
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {
                    Product product = displayedProducts.get(position);
                    CartItem removedItem = null;
                    
                    // 查找并移除购物车中的商品
                    for (CartItem item : cartManager.getCartItems()) {
                        if (item.getProduct().getId() == product.getId()) {
                            removedItem = item;
                            break;
                        }
                    }
                    
                    if (removedItem != null) {
                        // 记住商品和数量用于撤销操作
                        final CartItem finalRemovedItem = removedItem;
                        cartManager.removeCartItem(product);
                        
                        // 显示撤销Snackbar
                        Snackbar.make(recyclerViewProducts, "已从购物车移除 " + product.getName(), Snackbar.LENGTH_LONG)
                                .setAction("撤销", v -> {
                                    // 恢复商品到购物车
                                    cartManager.setProductQuantity(finalRemovedItem.getProduct(), finalRemovedItem.getQuantity());
                                })
                                .show();
                    }
                    
                    // 刷新适配器显示
                    productAdapter.notifyItemChanged(position);
                }
            }
        };
        
        // 将ItemTouchHelper附加到RecyclerView
        new ItemTouchHelper(simpleCallback).attachToRecyclerView(recyclerViewProducts);
    }

    // 设置按钮监听
    private void setupButtonClickListeners() {
        // 监听All Order button
        allOrderButton.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), AllOrderActivity.class);
            startActivity(intent);
        });

        // 监听 Submit Order Button
        submitOrderButton.setOnClickListener(v -> {
            List<CartItem> cartItems = cartManager.getCartItems();
            if (cartItems.isEmpty()) {
                Toast.makeText(getContext(), "请先选择商品", Toast.LENGTH_SHORT).show();
                return;
            }
            
            Intent intent = new Intent(getActivity(), OrderActivity.class);
            
            // 将选中商品信息格式化后传递
            StringBuilder orderDetails = new StringBuilder();
            for (CartItem cartItem : cartItems) {
                Product product = cartItem.getProduct();
                int quantity = cartItem.getQuantity();
                if (quantity > 0) {
                    orderDetails.append(product.getName())
                            .append(" x").append(quantity)
                            .append(" - ¥").append(String.format("%.2f", product.getPrice() * quantity))
                            .append("\n");
                }
            }
            
            intent.putExtra("order_details", orderDetails.toString());
            intent.putExtra("total_price", cartManager.getTotalPrice());
            startActivity(intent);
        });

        // 监听 Toggle Music Button
        toggleMusicButton.setOnClickListener(v -> {
            // 实现与 MainActivity 通信以控制 BGMService
            if (getActivity() instanceof MainActivity) {
                MainActivity activity = (MainActivity) getActivity();
                if (activity.isMusicPlaying()) {
                    activity.pauseMusic();
                    Toast.makeText(getContext(), "音乐已暂停", Toast.LENGTH_SHORT).show();
                } else {
                    activity.playMusic();
                    Toast.makeText(getContext(), "音乐已播放", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), "无法控制音乐播放", Toast.LENGTH_SHORT).show();
            }
        });
    }
    
    // 设置分类标签监听
    private void setupCategoryChips() {
        categoryChipGroup.setOnCheckedStateChangeListener((group, checkedIds) -> {
            if (checkedIds.isEmpty()) {
                // 如果没有选中项，默认选择"全部"
                Chip chipAll = group.findViewById(R.id.chip_all);
                chipAll.setChecked(true);
                return;
            }
            
            // 获取选中的标签
            Chip selectedChip = group.findViewById(checkedIds.get(0));
            if (selectedChip != null) {
                currentCategory = selectedChip.getText().toString();
                // 添加调试日志，记录选中的分类
                Log.d(TAG, "选中分类: '" + currentCategory + "'");
                filterProducts();
            }
        });
    }
    
    // 设置搜索功能
    private void setupSearch() {
        searchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 不需要实现
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 不需要实现
            }

            @Override
            public void afterTextChanged(Editable s) {
                searchQuery = s.toString().trim().toLowerCase();
                filterProducts();
            }
        });
    }
    
    // 根据分类和搜索关键词过滤商品
    private void filterProducts() {
        // 清空之前添加日志
        Log.d(TAG, "过滤商品前，当前displayedProducts大小: " + displayedProducts.size());
        displayedProducts.clear();
        
        // 添加调试日志，记录当前过滤条件
        Log.d(TAG, "开始过滤商品 - 当前分类: '" + currentCategory + "', 搜索关键词: '" + searchQuery + "'");
        Log.d(TAG, "商品总数: " + allProducts.size());
        
        for (Product product : allProducts) {
            // 使用更宽松的匹配规则：
            // 1. 如果选择"全部"分类，则显示所有商品
            // 2. 使用contains()而非equals()进行匹配，以应对可能的部分匹配
            // 3. 对分类名称进行trim()处理，去除可能的空格
            // 4. 保持大小写不敏感的比较
            
            String productCategory = (product.getCategory() != null) ? product.getCategory().trim() : "";
            String selectedCategory = currentCategory.trim();
            
            boolean matchesCategory = "全部".equals(selectedCategory) || 
                    (!productCategory.isEmpty() && 
                     (productCategory.toLowerCase().contains(selectedCategory.toLowerCase()) || 
                      selectedCategory.toLowerCase().contains(productCategory.toLowerCase())));
            
            // 添加调试日志，记录产品分类信息
            Log.d(TAG, "商品: " + product.getName() + ", 分类: '" + productCategory + 
                  "', 当前选择分类: '" + selectedCategory + "', 是否匹配: " + matchesCategory);
            
            boolean matchesSearch = searchQuery.isEmpty() || 
                    product.getName().toLowerCase().contains(searchQuery) || 
                    (product.getDescription() != null && 
                            product.getDescription().toLowerCase().contains(searchQuery));
            
            if (matchesCategory && matchesSearch) {
                displayedProducts.add(product);
                // 添加记录，显示添加的商品
                Log.d(TAG, "添加到显示列表: " + product.getName());
            }
        }
        
        // 添加日志，记录过滤后displayedProducts的大小
        Log.d(TAG, "过滤后，准备显示的商品数量: " + displayedProducts.size());
        
        // 更新适配器
        if (productAdapter != null) {
            productAdapter.updateProductList(new ArrayList<>(displayedProducts));
            
            // 显式调用通知数据集改变，以确保视图更新
            productAdapter.notifyDataSetChanged();
            
            // 确保UI线程上执行视图更新
            if (getView() != null) {
                getView().post(() -> {
                    // 检查列表是否为空并显示相应UI
                    checkIfEmpty();
                    
                    // 强制布局重新测量和绘制
                    recyclerViewProducts.requestLayout();
                });
            }
        } else {
            Log.e(TAG, "过滤商品时productAdapter为null");
        }
        
        Log.d(TAG, "过滤后显示 " + displayedProducts.size() + " 个商品");
    }

    // 更新购物车UI显示
    private void updateCartUI() {
        if (bottomCartTextView != null) {
            int totalItems = cartManager.getTotalItemCount();
            double totalPrice = cartManager.getTotalPrice();
            
            bottomCartTextView.setText("购物车：" + totalItems + "件, 共 ¥" + String.format("%.2f", totalPrice));
            
            // 更新购物车角标
            if (totalItems > 0) {
                cartBadge.setVisibility(View.VISIBLE);
                cartBadge.setText(String.valueOf(totalItems));
            } else {
                cartBadge.setVisibility(View.GONE);
            }
            
            // 启用或禁用结算按钮
            submitOrderButton.setEnabled(totalItems > 0);
        }
    }

    // 实现CartChangeListener接口的方法
    @Override
    public void onCartChanged(List<CartItem> cartItems, double totalPrice) {
        updateCartUI();
    }
    
    // 实现CartClearListener接口的方法
    @Override
    public void onCartCleared() {
        // 购物车被清空时，强制刷新所有商品项的数量显示
        if (productAdapter != null) {
            productAdapter.resetAllQuantityDisplays();
            
            // 遍历所有可见的商品视图，直接更新UI状态
            for (int i = 0; i < recyclerViewProducts.getChildCount(); i++) {
                View itemView = recyclerViewProducts.getChildAt(i);
                if (itemView != null) {
                    TextView quantityView = itemView.findViewById(R.id.product_quantity);
                    if (quantityView != null) {
                        quantityView.setText("0");
                    }
                    
                    ImageButton btnDecrease = itemView.findViewById(R.id.btn_decrease);
                    if (btnDecrease != null) {
                        btnDecrease.setVisibility(View.GONE);
                    }
                }
            }
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 保存购物车数据
        cartManager.saveCart(requireContext());
        // 移除监听器
        cartManager.removeCartChangeListener(this);
        cartManager.removeCartClearListener(this);
        // 关闭对话框
        if (cartDialog != null && cartDialog.isShowing()) {
            cartDialog.dismiss();
            cartDialog = null;
        }
        // 关闭数据库
        if (dbHelper != null) {
            dbHelper.close();
            dbHelper = null;
        }
    }
} 